<script setup>
  import {onMounted, onUpdated, ref, watch} from "vue";

  const props = defineProps({
    modelValue: {
      type: Number,
      default: 0
    },
    list: {
      type: Array,
      default: () => ['标题1', '标题2']
    }
  });

  const emits = defineEmits(['update:modelValue']);

  const titleRef = ref()
  const lineRef = ref()
  const isLineAction = ref(false)
  const isLine = ref(false)
  let w = 0
  let c = 0

  const moveLine = e => {
    lineRef.value.style.left = w * (e + 1) - w / 2 - c / 2 + 'px'
  }

  watch(props,() => {
    if (isLine.value) {
      //开启显示
      isLineAction.value = true;
    }
    isLine.value = true
  })

  onUpdated(() => {
    w = titleRef.value[0].clientWidth
    c = lineRef.value.clientWidth
    moveLine(props.modelValue)
  })

  const changeSelect = index => {
    moveLine(index)
    emits('update:modelValue', index)
  }
</script>

<template>
  <div class="tabs">
    <template v-for="(item,index) in list" :key="index">
      <div class="title" ref="titleRef" @click="changeSelect(index)"
           :class="{active:modelValue === index}">
          {{ item }}
      </div>
    </template>
    <div class="line" ref="lineRef" v-show="isLine" :style="{transition:isLineAction? .25 + 's':0}"></div>
  </div>
</template>

<style lang="less" scoped>
  .tabs {
    display: flex;
    align-items: center;
    height: 44px;
    position: relative;

    .title {
      flex: 1;
      display: flex;
      justify-content: center;

      &.active {
        font-weight: bold;
      }
    }

    .line {
      width: 30px;
      height: 2px;
      background: var(--primary-color);
      position: absolute;
      left: 0;
      bottom: 0;
    }
  }
</style>